package com.hellomaker.redismq.starter.config.parser;

import com.hellomaker.redismq.consume.GroupConsumer;
import com.hellomaker.redismq.consume.listener.ListenerContainer;
import com.hellomaker.redismq.core.mq.SimpleRedisMQClient;
import com.hellomaker.redismq.starter.config.ListenMessage;
import com.hellomaker.redismq.starter.config.ListenerAnnotationParser;
import com.hellomaker.redismq.starter.config.MessageListener;
import com.hellomaker.redismq.starter.config.listener.ListenerMethod;

import java.lang.reflect.Method;
import java.util.List;


public class ListenMessageParser implements ListenerAnnotationParser {
    SimpleRedisMQClient client;
    ListenerContainer<String, String> listenerContainer;

    public ListenMessageParser(SimpleRedisMQClient client, ListenerContainer<String, String> listenerContainer) {
        this.client = client;
        this.listenerContainer = listenerContainer;
    }

    @Override
    public void parseBean(Class<?> aClass, Object bean, String beanName) {
        if (ListenMessage.class.isAssignableFrom(aClass) && aClass.isAnnotationPresent(MessageListener.class)) {
            try {
                Method onMessageMethod = aClass.getDeclaredMethod("onMessage", GroupConsumer.class, List.class);
                MessageListener messageListener = aClass.getAnnotation(MessageListener.class);
                ListenerMethod listenerMethod = new ListenerMethod(client, listenerContainer, messageListener, onMessageMethod, bean);
                listenerMethod.doListen();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }
}
